package com.bestcem.xm.common.core.config.grpc;

import io.grpc.ManagedChannel;

import javax.validation.constraints.NotNull;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟关闭
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/16 16:10
 */
public class DelayedChannel implements Delayed {

    /**
     * grpc连接channel
     */
    private ManagedChannel managedChannel;

    /**
     * 延迟关闭时间 ms
     */
    private long executeTimeMiliSeconds;


    public DelayedChannel(ManagedChannel managedChannel, long timeOutMiliSeconds) {
        this.managedChannel = managedChannel;
        this.executeTimeMiliSeconds = System.currentTimeMillis() + timeOutMiliSeconds;
    }

    public long getExecuteTimeMiliSeconds() {
        return executeTimeMiliSeconds;
    }

    public ManagedChannel getManagedChannel() {
        return managedChannel;
    }

    @Override
    public long getDelay(@NotNull TimeUnit unit) {
        return unit.convert(executeTimeMiliSeconds - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(@NotNull Delayed o) {
        DelayedChannel other = (DelayedChannel)o;
        long diff = this.executeTimeMiliSeconds - other.executeTimeMiliSeconds;
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        } else {
            return -1;
        }
    }
}
